use std::{fs::OpenOptions, path::PathBuf};

use crate::base::Ftp;
use ftp::{FtpError, FtpStream};
pub struct FtpDownload {
    ftp_stream: FtpStream,
    dir: tempfile::TempDir,
}

impl FtpDownload {
    pub fn from_conf(conf: &Ftp) -> anyhow::Result<Self> {
        let addr = format!("{}:{}", conf.ip, conf.port);
        let mut ftp_stream = FtpStream::connect(&addr)?;
        ftp_stream.login(&conf.user_name, &conf.password)?;
        ftp_stream
            .cwd(&conf.path)
            .or_else(|err| Err(anyhow::anyhow!("切换路径{}出错:{}", &conf.path, err)))?;
        let dir=tempfile::tempdir()?;
        Ok(Self { ftp_stream,dir })
    }
    pub fn download(&mut self,file_name: &str) -> anyhow::Result<PathBuf> {
        let file_path = self.dir.path().join(file_name);
        self.ftp_stream.retr(&file_name, |stream| {
            let mut file = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&file_path).unwrap();
            std::io::copy(stream, &mut file).map_err(|e| FtpError::ConnectionError(e))
        }).or_else(|err|{
            Err(anyhow::anyhow!("下载文件{}出错:{}",&file_name,err))
        })?;
        Ok(file_path)
    }
    // pub fn is_exist(&mut self, file_name: &str) -> anyhow::Result<bool> {
    //     let list=self.ftp_stream
    //         .nlst(Some(file_name))?;
    //     Ok(list.len() > 0)
    // }
    pub fn close(&mut self) -> anyhow::Result<()> {
        self.ftp_stream.quit()?;
        Ok(())
    }
}

